package com.gitee.magic.core.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import com.gitee.magic.core.exception.ApplicationException;
import com.gitee.magic.core.utils.codec.Base64;

/**
 * @author start
 */
public class GzipComperssedUtils {
	
	/**
	 * 压缩返回Base64编码
	 * @param value
	 * @return
	 */
	public static String compressed(String value) {
		return Base64.encode(compressedToBytes(value));
	}
	
	/**
	 * 压缩
	 * @param value
	 * @return
	 */
	public static byte[] compressedToBytes(String value) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip = null;
		try {
			gzip = new GZIPOutputStream(out);
			gzip.write(value.getBytes());
		} catch (IOException e) {
			throw new ApplicationException(e);
		} finally {
			if (gzip != null) {
				try {
					gzip.close();
				} catch (IOException e) {
					throw new ApplicationException(e);
				}
			}
		}
		return out.toByteArray();
	}

	/**
	 * 解压缩 Base64数据
	 * @param value
	 * @return
	 */
	public static byte[] decompressed(String value) {
		return decompressedByBytes(Base64.decode(value));
	}

	/**
	 * 解压缩
	 * @param bytes
	 * @return
	 */
	public static byte[] decompressedByBytes(byte[] bytes) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = null;
		GZIPInputStream ginzip = null;
		try {
			in = new ByteArrayInputStream(bytes);
			ginzip = new GZIPInputStream(in);
			byte[] buffer = new byte[1024];
			int offset = -1;
			while ((offset = ginzip.read(buffer)) != -1) {
				out.write(buffer, 0, offset);
			}
			return out.toByteArray();
		} catch (IOException e) {
			throw new ApplicationException(e);
		} finally {
			if (ginzip != null) {
				try {
					ginzip.close();
				} catch (IOException e) {
					throw new ApplicationException(e);
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					throw new ApplicationException(e);
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					throw new ApplicationException(e);
				}
			}
		}
	}
	
}
